/* eslint-disable no-loop-func */
let addGeoJsonData = []
let labelsData = []

function addGeoJson(urlStr, colorStr, callback) {
	let entity = null
	if (!urlStr) return

	Cesium.GeoJsonDataSource.load(urlStr).then((dataSource) => {
		let color
		for (let i = 0; i < dataSource.entities.values.length; ++i) {
			entity = dataSource.entities.values[i]
			if (!entity.polygon) continue
			color = Cesium.Color.fromCssColorString(colorStr).withAlpha(0.1)

			entity.polygon = new Cesium.PolygonGraphics({
				hierarchy: entity.polygon.hierarchy._value,
				outline: false,
				material: color,
				classificationType: Cesium.ClassificationType.TERRAIN,
				zIndex: 10
			})

			entity.polyline = new Cesium.PolylineGraphics({
				positions: [...entity.polygon.hierarchy._value.positions, entity.polygon.hierarchy._value.positions[0]],
				width: 1,
				material: Cesium.Color.fromCssColorString(colorStr),
				clampToGround: true,
				classificationType: Cesium.ClassificationType.TERRAIN
				// zIndex:1
			})

			let index = labelsData.find((item) => {
				return item.name == entity.name
			})
			if (entity.properties.centroid && !index) {
				let label = viewer.entities.add({
					position: Cesium.Cartesian3.fromDegrees(entity.properties.centroid._value[0], entity.properties.centroid._value[1]),
					label: {
						font: '14px sans-serif',
						text: entity.name,
						showBackground: true,
						scale: 1,
						horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
						verticalOrigin: Cesium.VerticalOrigin.BOTTOM
					}
				})
				label.name = entity.name
				labelsData.push(label)
			}

			entity.cursor = true
			// let holes = entity.polygon.hierarchy._value.holes
			// for (let j = 0; j < holes.length; ++j) {
			// 	dataSource.entities.add({
			// 		polyline: {
			// 			positions: [...holes[j].positions, holes[j].positions[0]],
			// 			width: 3,
			// 			clampToGround: true,
			// 			material: color,
			// 			classificationType: Cesium.ClassificationType.TERRAIN,
			// 			zIndex: 1,
			// 		},
			// 	})
			// }
		}

		addGeoJsonData.push(dataSource)
		viewer.dataSources.add(dataSource)
		callback(dataSource.entities.values)
	})
}

function removeGeoJson() {
	for (let i = 0; i < addGeoJsonData.length; ++i) {
		viewer.dataSources.remove(addGeoJsonData[i])
	}
	addGeoJsonData.length = 0
	addGeoJsonData = []
	for (let j = 0; j < labelsData.length; j++) {
		viewer.entities.remove(labelsData[j])
	}
	labelsData = []
}
export { addGeoJson, removeGeoJson }
